<?php
// 在文件最顶部启动会话，确保没有任何输出
session_start();

// 检查登录状态
$isLoggedIn = isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
$userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>短视频去水印小工具</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }
        .container {
            max-width: 800px;
        }
        .card {
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            border: none;
            overflow: hidden;
        }
        .card-header {
            background: linear-gradient(45deg, #6c5ce7, #a29bfe);
            color: white;
            text-align: center;
            padding: 20px;
        }
        .card-body {
            padding: 25px;
        }
        .form-control:focus {
            border-color: #6c5ce7;
            box-shadow: 0 0 0 0.25rem rgba(108, 92, 231, 0.25);
        }
        .btn-primary {
            background: linear-gradient(45deg, #6c5ce7, #a29bfe);
            border: none;
            padding: 12px;
            font-weight: 600;
            transition: all 0.3s;
        }
        .btn-primary:hover {
            background: linear-gradient(45deg, #5b4cdb, #8f86f5);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(108, 92, 231, 0.3);
        }
        #loadingSpinner {
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        #loadingSpinner.show {
            opacity: 1;
        }
        .result-card {
            margin-top: 20px;
            border-radius: 10px;
            overflow: hidden;
        }
        .video-container {
            position: relative;
            padding-top: 56.25%; /* 16:9 Aspect Ratio */
            border-radius: 8px;
            overflow: hidden;
            background-color: #000;
        }
        .video-container video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
            margin-top: 15px;
        }
        .image-item {
            border-radius: 8px;
            overflow: hidden;
            position: relative;
            cursor: pointer;
            transition: transform 0.3s;
        }
        .image-item:hover {
            transform: scale(1.03);
        }
        .image-item img {
            width: 100%;
            height: 150px;
            object-fit: cover;
        }
        .author-info {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        .author-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
            object-fit: cover;
        }
        .badge-platform {
            background: linear-gradient(45deg, #fd79a8, #e84393);
            color: white;
            font-size: 0.75rem;
            padding: 4px 8px;
            border-radius: 20px;
            margin-left: 10px;
        }
        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        .btn-action {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 5px;
        }
        .modal-content {
            border-radius: 12px;
            overflow: hidden;
        }
        #modalImage {
            max-height: 80vh;
            width: auto;
            max-width: 100%;
        }
        .media-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 10;
        }
        .cors-notice {
            font-size: 0.85rem;
            color: #6c757d;
            background-color: #f8f9fa;
            padding: 8px 12px;
            border-radius: 4px;
            margin-top: 10px;
        }
        .balance-info {
            background-color: #e9ecef;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .video-error {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: white;
        }
        @media (max-width: 576px) {
            .card-body {
                padding: 15px;
            }
            .image-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div class="container mt-4">
        <!-- 导航栏 -->
        <nav class="navbar navbar-expand-lg navbar-light bg-light mb-4">
            <div class="container">
                <a class="navbar-brand" href="index.php">小工具主页</a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav">
                        <?php if (!$isLoggedIn) : ?>
                            <li class="nav-item">
                                <a class="nav-link" href="login.html">登录</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="register.html">注册</a>
                            </li>
                        <?php else : ?>
                            <li class="nav-item">
                                <a class="nav-link" href="user-center.php">用户中心</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" href="logout.php">退出</a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </div>
            </div>
        </nav>

        <div class="card">
            <div class="card-header">
                <h2 class="mb-0"><i class="fas fa-water me-2"></i>短视频去水印小工具</h2>
                <p class="mb-0 mt-2">支持抖音、小红书、快手、皮皮虾、最右、皮皮搞笑和微视</p>
            </div>
            <div class="card-body">
                <?php if (!$isLoggedIn) : ?>
                    <div class="alert alert-warning" role="alert">
                        <i class="fas fa-exclamation-triangle me-2"></i>请先<a href="login.html" class="alert-link">登录</a>后使用本工具
                    </div>
                <?php else : 
                    // 获取用户余额
                    include 'includes/db.php';
                    $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
                    $stmt->execute([$userId]);
                    $user = $stmt->fetch();
                    $balance = $user ? $user['balance'] : 0;
                ?>
                    <div class="balance-info">
                        <span>当前余额: <strong><?php echo $balance; ?></strong> 积分</span>
                        <a href="recharge.php" class="btn btn-sm btn-success">充值</a>
                    </div>
                    
                    <form id="removeWatermarkForm">
                        <div class="mb-3">
                            <label for="videoUrl" class="form-label">输入短视频链接</label>
                            <textarea class="form-control" id="videoUrl" name="url" rows="3" placeholder="请输入短视频链接或包含链接的文本" required></textarea>
                        </div>
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="fas fa-magic me-2"></i>一键解析去水印
                        </button>
                        <div id="loadingSpinner" class="text-center mt-3 d-none">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p class="mt-2">正在解析中，请稍候...</p>
                        </div>
                    </form>
                    <div id="result" class="mt-4"></div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="modal fade" id="imageModal" tabindex="-1" aria-labelledby="imageModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="imageModalLabel">图片预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <img src="" alt="图片预览" class="img-fluid" id="modalImage">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="downloadImage">下载图片</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="videoModal" tabindex="-1" aria-labelledby="videoModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="videoModalLabel">视频预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body text-center">
                    <div class="video-container">
                        <video controls id="modalVideo">
                            <source src="" type="video/mp4">
                            您的浏览器不支持HTML5视频播放
                        </video>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="downloadVideo">下载视频</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量存储当前媒体数据
        let currentMediaData = null;
        let currentImageUrl = '';
        
        // 检查登录状态
        <?php if (!$isLoggedIn) : ?>
            // 如果未登录，禁用表单提交
            document.addEventListener('DOMContentLoaded', function() {
                document.getElementById('removeWatermarkForm')?.addEventListener('submit', function(e) {
                    e.preventDefault();
                    window.location.href = 'login.html';
                });
            });
        <?php else : ?>
            // 如果已登录，设置表单提交事件
            document.getElementById('removeWatermarkForm').addEventListener('submit', function(event) {
                event.preventDefault();
                
                // 显示加载动画
                document.getElementById('loadingSpinner').classList.remove('d-none');
                document.querySelector('button[type="submit"]').disabled = true;
                
                const inputContent = document.getElementById('videoUrl').value;
                const linkRegex = /https?:\/\/[^\s]+/g;
                const links = inputContent.match(linkRegex) || [];
                
                if (links.length === 0) {
                    document.getElementById('result').innerHTML = `
                        <div class="alert alert-warning" role="alert">
                            <i class="fas fa-exclamation-triangle me-2"></i>未找到有效的链接，请检查输入内容
                        </div>
                    `;
                    document.getElementById('loadingSpinner').classList.add('d-none');
                    document.querySelector('button[type="submit"]').disabled = false;
                    return;
                }
                
                const videoUrl = links[0];
                
                // 使用服务器端代理获取视频数据
                fetch(`remove.php?url=${encodeURIComponent(videoUrl)}`, {
                    method: 'GET',
                    credentials: 'same-origin'
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        currentMediaData = data.data;
                        displayResult(data.data, videoUrl);
                        
                        // 更新余额显示
                        if (data.balance !== undefined) {
                            document.querySelector('.balance-info strong').textContent = data.balance;
                        }
                    } else {
                        document.getElementById('result').innerHTML = `
                            <div class="alert alert-danger" role="alert">
                                <i class="fas fa-times-circle me-2"></i>${data.message}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('result').innerHTML = `
                        <div class="alert alert-danger" role="alert">
                            <i class="fas fa-times-circle me-2"></i>请求失败: ${error.message}
                            <div class="cors-notice mt-2">
                                <i class="fas fa-info-circle me-1"></i>如果遇到跨域问题，请尝试刷新页面或联系管理员。
                            </div>
                        </div>
                    `;
                })
                .finally(() => {
                    document.getElementById('loadingSpinner').classList.add('d-none');
                    document.querySelector('button[type="submit"]').disabled = false;
                });
            });
        <?php endif; ?>

        function displayResult(data, originalUrl) {
            let resultHtml = `
                <div class="card result-card">
                    <div class="card-body">
                        <div class="author-info">
                            <img src="${data.author.avatar || data.cover_url || 'https://via.placeholder.com/40'}" class="author-avatar" alt="作者头像" onerror="this.src='https://via.placeholder.com/40'">
                            <div>
                                <strong>${data.author.nickname || data.author || '未知作者'}</strong>
                                <span class="badge-platform">${getPlatformName(originalUrl)}</span>
                            </div>
                        </div>
                        <h5 class="card-title">${data.title || '无标题'}</h5>
            `;
            
            // 根据媒体类型显示不同内容
            if (data.type === 1 || (data.type === 3 && data.video_url)) {
                // 视频内容 - 使用代理URL
                const proxyVideoUrl = `proxy.php?url=${encodeURIComponent(data.video_url)}&type=video`;
                const directVideoUrl = data.video_url; // 原始URL作为备选
                
                // 生成安全的文件名
                const safeTitle = data.title ? data.title.replace(/[^\w\u4e00-\u9fa5]/g, '_').substring(0, 50) : 'video';
                const timestamp = new Date().getTime();
                const videoFilename = `${safeTitle}_${timestamp}.mp4`;
                
                resultHtml += `
                    <div class="video-container mb-3">
                        <video controls class="w-100" crossorigin="anonymous" onerror="handleVideoError(this, '${directVideoUrl}')">
                            <source src="${proxyVideoUrl}" type="video/mp4">
                            <source src="${directVideoUrl}" type="video/mp4">
                            您的浏览器不支持HTML5视频播放
                        </video>
                        <div class="video-error d-none" id="videoError">
                            <i class="fas fa-exclamation-triangle fa-2x mb-2"></i>
                            <p>视频加载失败，请尝试下载或复制链接</p>
                        </div>
                        <div class="media-badge">视频</div>
                    </div>
                    <div class="action-buttons">
                        <button class="btn btn-success btn-action" onclick="playVideoInModal('${data.video_url}', '${safeTitle}')">
                            <i class="fas fa-expand me-1"></i>全屏播放
                        </button>
                        <button class="btn btn-primary btn-action" onclick="copyToClipboard('${data.video_url}', '视频链接')">
                            <i class="fas fa-copy me-1"></i>复制链接
                        </button>
                        <button class="btn btn-info btn-action" onclick="downloadWithRetry('${data.video_url}', 'video', '${videoFilename}')">
                            <i class="fas fa-download me-1"></i>下载视频
                        </button>
                        <button class="btn btn-warning btn-action" onclick="openDirectLink('${data.video_url}')">
                            <i class="fas fa-external-link-alt me-1"></i>直接打开
                        </button>
                    </div>
                    <div class="cors-notice">
                        <i class="fas fa-info-circle me-1"></i>如果视频无法播放，请尝试"直接打开"或"下载视频"。
                    </div>
                `;
            }
            
            if (data.type === 2 || (data.type === 3 && data.pics && data.pics.length > 0)) {
                // 图片内容 - 使用代理URL
                const images = data.pics || [];
                if (images.length > 0) {
                    const safeTitle = data.title ? data.title.replace(/[^\w\u4e00-\u9fa5]/g, '_').substring(0, 30) : 'image';
                    const timestamp = new Date().getTime();
                    
                    resultHtml += `
                        <h6 class="mt-4">图片内容 (${images.length}张)</h6>
                        <div class="image-grid">
                    `;
                    
                    images.forEach((img, index) => {
                        const proxyImgUrl = `proxy.php?url=${encodeURIComponent(img)}&type=image`;
                        const imageFilename = `${safeTitle}_${index + 1}_${timestamp}.jpg`;
                        
                        resultHtml += `
                            <div class="image-item position-relative">
                                <img src="${proxyImgUrl}" alt="图片 ${index + 1}" 
                                     onclick="showImageInModal('${img}', '${imageFilename}')" 
                                     crossorigin="anonymous"
                                     onerror="this.src='https://via.placeholder.com/150?text=图片加载失败'">
                                <div class="media-badge">图片 ${index + 1}</div>
                            </div>
                        `;
                    });
                    
                    resultHtml += `
                        </div>
                        <div class="action-buttons mt-3">
                            <button class="btn btn-primary btn-action" onclick="downloadAllImages([${images.map(img => `'${img}'`).join(',')}], '${safeTitle}')">
                                <i class="fas fa-download me-1"></i>打包下载图片
                            </button>
                        </div>
                    `;
                }
            }
            
            resultHtml += `
                    </div>
                </div>
            `;
            
            document.getElementById('result').innerHTML = resultHtml;
            
            // 添加视频错误处理
            const videoElement = document.querySelector('video');
            if (videoElement) {
                videoElement.addEventListener('error', function() {
                    const errorDiv = this.parentNode.querySelector('.video-error');
                    if (errorDiv) {
                        errorDiv.classList.remove('d-none');
                    }
                });
            }
        }
        
        function getPlatformName(url) {
            if (url.includes('douyin')) return '抖音';
            if (url.includes('xhslink')) return '小红书';
            if (url.includes('kuaishou')) return '快手';
            if (url.includes('pipix')) return '皮皮虾';
            if (url.includes('xiaochuankeji')) return '最右';
            if (url.includes('pipigx')) return '皮皮搞笑';
            if (url.includes('weishi')) return '微视';
            if (url.includes('xiaohongshu')) return '小红书';
            return '未知平台';
        }
        
        function playVideoInModal(videoUrl) {
            const proxyVideoUrl = `proxy.php?url=${encodeURIComponent(videoUrl)}&type=video`;
            const videoModal = new bootstrap.Modal(document.getElementById('videoModal'));
            const videoElement = document.getElementById('modalVideo');
            const sourceElement = videoElement.querySelector('source');
            
            sourceElement.src = proxyVideoUrl;
            videoElement.load();
            
            // 设置下载按钮
            document.getElementById('downloadVideo').onclick = function() {
                downloadWithRetry(videoUrl, 'video', 'video_download');
            };
            
            videoModal.show();
        }
        
       
        
        function copyToClipboard(text, type) {
            navigator.clipboard.writeText(text).then(() => {
                alert(`${type}已复制到剪贴板！`);
            }).catch(err => {
                console.error('复制失败:', err);
                // 使用传统方法作为备选
                const textArea = document.createElement("textarea");
                textArea.value = text;
                document.body.appendChild(textArea);
                textArea.select();
                try {
                    document.execCommand('copy');
                    alert(`${type}已复制到剪贴板！`);
                } catch (e) {
                    alert('复制失败，请手动复制');
                }
                document.body.removeChild(textArea);
            });
        }
        
        // 生成安全的文件名
        function generateSafeFilename(title, type, index = null, total = null) {
            // 清理文件名中的非法字符
            let safeName = title.replace(/[^\w\u4e00-\u9fa5]/g, '_');
            safeName = safeName.substring(0, 50); // 限制长度
            
            const timestamp = new Date().getTime();
            const random = Math.random().toString(36).substring(2, 8);
            
            let filename = safeName;
            
            if (total && total > 1) {
                // 多文件情况
                filename += `_${index + 1}of${total}`;
            }
            
            filename += `_${timestamp}_${random}`;
            
            // 添加文件扩展名
            const extensions = {
                'video': 'mp4',
                'image': 'jpg'
            };
            
            return `${filename}.${extensions[type] || 'bin'}`;
        }
        
        // 增强的下载函数
        function downloadWithRetry(url, type, customFilename = null, retryCount = 0) {
            const maxRetries = 2;
            
            // 生成文件名
            let filename;
            if (customFilename) {
                filename = customFilename;
            } else {
                // 从URL中提取可能的文件名
                const urlParts = url.split('/');
                const lastPart = urlParts[urlParts.length - 1];
                const baseName = lastPart.split('?')[0].split('.')[0] || 'download';
                filename = generateSafeFilename(baseName, type);
            }
            
            // 使用代理下载
            const proxyUrl = `proxy.php?url=${encodeURIComponent(url)}&type=download&filename=${encodeURIComponent(filename)}`;
            
            // 创建一个临时链接进行下载
            const a = document.createElement('a');
            a.href = proxyUrl;
            a.download = filename;
            a.target = '_blank';
            document.body.appendChild(a);
            
            // 处理下载错误
            a.onerror = function() {
                if (retryCount < maxRetries) {
                    // 重试下载
                    setTimeout(() => {
                        downloadWithRetry(url, type, customFilename, retryCount + 1);
                    }, 1000 * (retryCount + 1));
                } else {
                    alert('下载失败，请尝试右键链接另存为');
                    // 直接打开链接作为备选方案
                    window.open(url, '_blank');
                }
            };
            
            a.click();
            document.body.removeChild(a);
        }
        
        // 下载所有图片
        function downloadAllImages(imageUrls, title) {
            if (!imageUrls || imageUrls.length === 0) return;
            
            alert(`开始下载 ${imageUrls.length} 张图片，请稍候...`);
            
            // 逐个下载图片
            imageUrls.forEach((url, index) => {
                setTimeout(() => {
                    const filename = generateSafeFilename(title, 'image', index, imageUrls.length);
                    downloadWithRetry(url, 'image', filename);
                }, index * 500); // 间隔500ms避免浏览器阻塞
            });
        }
        
        // 修改模态框相关函数
        function playVideoInModal(videoUrl, title) {
            const proxyVideoUrl = `proxy.php?url=${encodeURIComponent(videoUrl)}&type=video`;
            const videoModal = new bootstrap.Modal(document.getElementById('videoModal'));
            const videoElement = document.getElementById('modalVideo');
            const sourceElement = videoElement.querySelector('source');
            
            sourceElement.src = proxyVideoUrl;
            videoElement.load();
            
            // 设置下载按钮
            const filename = generateSafeFilename(title, 'video');
            document.getElementById('downloadVideo').onclick = function() {
                downloadWithRetry(videoUrl, 'video', filename);
            };
            
            videoModal.show();
        }
        
        function showImageInModal(imageUrl, filename) {
            const proxyImageUrl = `proxy.php?url=${encodeURIComponent(imageUrl)}&type=image`;
            const imageModal = new bootstrap.Modal(document.getElementById('imageModal'));
            document.getElementById('modalImage').src = proxyImageUrl;
            
            // 设置下载按钮
            document.getElementById('downloadImage').onclick = function() {
                downloadWithRetry(imageUrl, 'image', filename);
            };
            
            imageModal.show();
        }
    </script>
</body>
</html>